<template>
  <div class="lists">
    <draggable :list="items" animation="300" item-key="key" tag="ul">
      <template #item="{ element, index }">
        <li class="todo-item">
          <input type="checkbox" v-model="element.checked" @change="handleCheckChange(index)" />
          <span v-if="!element.isEditing" :class="{ del: element.checked }" @click="handleEditMode(index)">
            {{ element.key }}
          </span>
          <input
            v-if="element.isEditing"
            type="text"
            class="update"
            v-model="element.newKey"
            @blur="handleUpdate(index)"
            @keyup.enter="handleUpdate(index)" />
          <button @click="handleDelete(index)">删除</button>
        </li>
      </template>
    </draggable>
  </div>
</template>

<script setup>
import { inject, ref } from 'vue';
import draggable from 'vuedraggable';

// 注入父组件提供的待办事项、删除和修改方法
const items = inject('items');
const handleDelete = inject('handleDelete');
const handleEdit = inject('handleEdit');

// 切换编辑模式
const handleEditMode = index => {
  // 先将所有其他项的编辑模式关闭
  items.value.forEach((item, i) => {
    if (i !== index) {
      item.isEditing = false;
    }
  });

  // 设置当前项为编辑模式
  items.value[index].isEditing = true;
  items.value[index].newKey = items.value[index].key; // 初始化新值为当前值
};

// 更新待办事项
const handleUpdate = index => {
  const newValue = items.value[index].newKey;
  handleEdit(index, newValue);
  // 退出编辑模式
  items.value[index].isEditing = false;

  // 按 checked 状态排序
  items.value.sort((a, b) => a.checked - b.checked);
};

// 更新 checked 状态，并同步到 localStorage
const handleCheckChange = index => {
  const itemKey = items.value[index].key;
  localStorage.setItem(itemKey, items.value[index].checked); // 更新 checked 状态
  items.value.sort((a, b) => a.checked - b.checked); // 排序
};
</script>

<style scoped>
.lists {
  position: relative;
}

.lists ul {
  width: 100%;
  list-style: none;
  padding: 0;
  margin: 0;
}

.lists .todo-item {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #ccc;
}

.lists input[type='checkbox'] {
  margin-left: 10px;
}

.lists span {
  flex: 1;
  margin-left: 40px;
  height: 40px;
  line-height: 40px;
}

.lists span.del {
  text-decoration: line-through;
  color: red;
}

.lists .update {
  flex: 1;
  margin-left: 40px;
  height: 20px;
  line-height: 20px;
  color: blue;
  border-radius: 3px;
}

.lists button {
  margin-left: 10px;
  margin-right: 40px;
  width: 60px;
  height: 30px;
  border: 1px solid black;
  border-radius: 3px;
  cursor: pointer;
}
</style>
